import React, { Component } from 'react';
import { Form, Button, Input, Table, Select } from 'antd';
// import * as promiseAjax from 'sx-ui/utils/promise-ajax';
import {FetchAPI} from '../../utils/fetch-middleware'

import './style.less';

const FormItem = Form.Item;
const Option = Select.Option;

export const PAGE_ROUTE = '/deal';

@Form.create()
export default class Deal extends Component {
    state = {
        dataSource: [],             // 记录列表数据
        selectedRowKeys: [],        // 被选择列
    }

    // 记录列表表头
    columns = [{
        key: 'loanSign',
        title: '借贷标志',
        dataIndex: 'loanSign',
    }, {
        key: 'accountType',
        title: '账户类型',
        dataIndex: 'accountType',
        render: (text, record, index) => {
            return (
                <FormItem>
                    {this.props.form.getFieldDecorator(`accountType${index}`, {
                        rules: [{required: true, message: '不能为空'}],
                    })(
                        <Select onChange={(value) => this.onValueChange(value, index, 'accountType')}>
                            <Option value="1">用户</Option>
                            <Option value="2">内部</Option>
                            <Option value="3">银行</Option>
                        </Select>
                    )}
                </FormItem>
            );
        },
    }, {
        key: 'subTcd',
        title: '子交易码',
        dataIndex: 'subTcd',
        render: (text, record, index) => {
            return (
                <FormItem>
                    {this.props.form.getFieldDecorator(`subTcd${Math.floor(index / 2)}`, {
                        rules: [{required: true, message: '不能为空'}],
                        initialValue: text,
                    })(<Input readOnly />)}
                </FormItem>
            );
        },
    }, {
        key: 'sbjNo',
        title: '科目号',
        dataIndex: 'sbjNo',
        render: (text, record, index) => {
            return (
                <FormItem>
                    {this.props.form.getFieldDecorator(`sbjNo${index}`, {
                        rules: [{required: true, message: '不能为空'}],
                    })(<Input onChange={(e) => this.onValueChange(e.target.value, index, 'sbjNo')} />)}
                </FormItem>
            );
        },
    }, {
        key: 'subName',
        title: '子交易名称',
        dataIndex: 'subName',
        render: (text, record, index) => {
            return (
                <FormItem>
                    {this.props.form.getFieldDecorator(`subName${Math.floor(index / 2)}`, {
                        rules: [{required: true, message: '不能为空'}],
                    })(<Input onChange={(e) => this.onValueChange(e.target.value, index, 'subName')} />)}
                </FormItem>
            );
        },
    }, {
        key: 'fundType',
        title: '资金类型',
        dataIndex: 'fundType',
        render: (text, record, index) => {
            return (
                <FormItem>
                    {this.props.form.getFieldDecorator(`fundType${Math.floor(index / 2)}`, {
                        rules: [{required: true, message: '不能为空'}],
                    })(
                        <Select onChange={(value) => this.onValueChange(value, index, 'fundType')}>
                            <Option value="1">交易额</Option>
                            <Option value="2">手续费</Option>
                            <Option value="3">分润金额</Option>
                            <Option value="4">分润手续费</Option>
                        </Select>
                    )}
                </FormItem>
            );
        },
    }]

    onValueChange = (value, index, item) => {
        const {dataSource} = this.state;
        console.log(dataSource, value, index, item);
        dataSource[index][item] = value;
        if (item === 'subName' || item === 'fundType') {
            dataSource[index - 1][item] = value;
        }
        this.setState({ dataSource });
    }

    // 添加
    onAdd = () => {
        this.props.form.validateFields(['mainCode'], (err, values) => {
            if (!err) {
                let {dataSource} = this.state;
                dataSource = dataSource.concat([{
                    key: dataSource.length,
                    tcd: values.mainCode,
                    loanSign: 'D',
                    subTcd: `${values.mainCode}${dataSource.length < 10 ? '0' : ''}${(dataSource.length / 2) + 1}`,
                }, {
                    key: dataSource.length + 1,
                    tcd: values.mainCode,
                    loanSign: 'C',
                    subTcd: `${values.mainCode}${dataSource.length < 10 ? '0' : ''}${(dataSource.length / 2) + 1}`,
                }]);
                this.setState({ dataSource });
            }
        });
    }

    // 删除
    onDel = () => {
        let {dataSource, selectedRowKeys} = this.state;
        dataSource = dataSource.filter(item => {
            let b = true;
            selectedRowKeys.forEach(index => {
                if (item.key === index) {
                    b = false;
                }
            });
            return b;
        });
        dataSource = dataSource.map((item, index) => {
            item.key = index;
            return item;
        });
        this.setState({ dataSource, selectedRowKeys: [] });
    }

    // 验证
    onCheck = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let sendValue = JSON.parse(JSON.stringify(this.state.dataSource));
                sendValue = sendValue.map(item => {
                    delete item.key;
                    return item;
                });
                console.log(sendValue, 'values');
                FetchAPI('/acc/valid', 'POST', sendValue)
            }
        });
    }

    render() {
        const {dataSource, selectedRowKeys} = this.state;
        const {getFieldDecorator} = this.props.form;
        const formLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 4},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 8},
            },
        };
        const rowSelection = {
            selectedRowKeys,
            onChange: (keys) => {
                const lastKey = keys[keys.length - 1];
                if ((this.state.selectedRowKeys.length < keys.length) || this.state.selectedRowKeys.length === 0) {
                    keys.push(lastKey % 2 === 0 ? lastKey + 1 : lastKey - 1);
                } else if (this.state.selectedRowKeys.length > keys.length) {
                    keys.pop();
                }
                this.setState({ selectedRowKeys: keys });
            },
        };
        return (
            <div className="page">
                <div className="deal">
                    <div className="deal-btnItem">
                        <Button onClick={this.onAdd}>添加</Button>
                        <Button onClick={this.onDel}>删除</Button>
                        <Button onClick={this.onCheck}>验证</Button>
                    </div>
                    <Form className="deal-mianCode">
                        <FormItem label="主交易码" {...formLayout}>
                            {getFieldDecorator('mainCode', {
                                rules: [{required: true, message: '请输入主交易码！'}],
                            })(
                                <Input readOnly={dataSource.length !== 0} />
                            )}
                        </FormItem>
                    </Form>
                    <div className="deal-table">
                        会员记录列表：
                        <Table
                            rowSelection={rowSelection}
                            bordered
                            pagination={false}
                            columns={this.columns}
                            dataSource={dataSource}
                        />
                    </div>
                </div>
            </div>
        );
    }
}